package com.fang.excel.controller;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 线程不安全实战
 */
public class HashMapUnsafeExample {
    private static final int THREAD_COUNT = 10;
    private static final int OPERATIONS_PER_THREAD = 1000;

    public static void main(String[] args) {
        Map<Integer, Integer> map = new HashMap<>();
        ExecutorService executor = Executors.newFixedThreadPool(THREAD_COUNT);

        // 创建多个线程，每个线程对 HashMap 进行写操作
        for (int i = 0; i < THREAD_COUNT; i++) {
            executor.submit(() -> {
                for (int j = 0; j < OPERATIONS_PER_THREAD; j++) {
                    map.put(j, j);
                }
            });
        }

        executor.shutdown();
        while (!executor.isTerminated()) {
            // 等待所有线程完成
        }

        // 打印 HashMap 的大小
        System.out.println("Map size: " + map.size());
    }
}
